package cn.edu.tju.se.auth.web.controller;
import java.io.File;
import java.sql.Timestamp;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tju.se.auth.dao.UserDao;
import cn.edu.tju.se.auth.domain.User;
import cn.edu.tju.se.auth.service.UserService;
import cn.edu.tju.se.base.cons.CommonConstant;
import cn.edu.tju.se.base.service.DateAdapter;
import cn.edu.tju.se.base.service.FileManager;
import cn.edu.tju.se.base.service.SendMail;
import cn.edu.tju.se.base.web.controller.BaseController;
import cn.edu.tju.se.records.domain.Patient;
import cn.edu.tju.se.records.domain.Photo;

import cn.edu.tju.se.records.service.PhotoService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


/**
 * <br>
 * <b>类描述:</b>
 * <pre>
 *   景区登录控制器，处理登录验证、注销等操作
 * </pre>
 * @see
 * @since
 */
@Controller
@RequestMapping("/auth")
public class LoginController extends BaseController {

	private static final String SITE_WIDE_SECRET = "TJKQZJK";
	private static final PasswordEncoder encoder = new StandardPasswordEncoder(
			SITE_WIDE_SECRET);
	/**
	 * 自动注入
	 */
	@Autowired
	private UserService userService;

	@Autowired
	private PhotoService photoService;

	
	/**
	 * 用户登录
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
    @RequestMapping(method=RequestMethod.POST, value="/login")
	public String login(HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) {
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		//User user = userService.findUserByUserName(userName);
		User user = userService.findUserByUserId(userName);
		if (user == null) {
			request.setAttribute("errorMsg", "用户名不存在");
			return "forward:/login.html";
		} else if (!userService.checkPassword(password, user)) {
			request.setAttribute("errorMsg", "用户密码不正确");
			return "forward:/login.html";
		} else {
			setSessionUser(request,user);
			
			return "forward:/welcome.html";
		}
	}

    /**
     *登录注销
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpSession session) {
		User user = getSessionUser(request);
		String cachePath = photoService.getImgPath() + "/cache";
		File cacheFile = new File(cachePath);
		FileManager test = new FileManager();
		test.deleteAll(cacheFile);
		session.removeAttribute(CommonConstant.USER_CONTEXT);
        return "forward:/login.html";
    }
    
    @RequestMapping(method=RequestMethod.POST, value="/register")
    public @ResponseBody Map register(HttpServletRequest request, @RequestBody String body){
		Map map = new HashMap<String ,String >();
		String msg = "";
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();

		User user = gson.fromJson(body, User.class);
		if(userService.findUserByUserId(user.getUserid())!=null){
			msg = "用户ID已注册";
		}else if(userService.findUserByUseremail(user.getUseremail())!=null){
			msg = "用户email已被使用";
		}else{
			msg = "添加新用户成功";
			userService.save(user);
		}
		map.put("msg",msg);
    	return map;
    }
    
    @RequestMapping(method=RequestMethod.GET, value="/currentuser")
	public @ResponseBody String getUserName(HttpServletRequest request) {	
    	User user = getSessionUser(request);
		return user.getUsername();
	}

	@RequestMapping(method=RequestMethod.POST, value="/forgetPass/{userid}")
	public @ResponseBody Map forgetPassWord(HttpServletRequest request,@PathVariable String userid) {
		//String userid = request.getParameter("userid");
		User user = userService.findUserByUserId(userid);
		String msg = "";
		Map map = new HashMap<String ,String >();
		if(user == null){              //用户名不存在
			msg = "用户名不存在,你不会忘记用户名了吧?";
			map.put("msg",msg);
			return map;
		}
		try{
			String secretKey= UUID.randomUUID().toString();  //密钥
			Timestamp outDate = new Timestamp(System.currentTimeMillis()+30*60*1000);//30分钟后过期
			long date = outDate.getTime()/1000*1000;
			user.setOutdate(outDate);
			user.setValidatecode(secretKey);
			userService.update(user);
			String key = user.getUsername()+"$"+date+"$"+secretKey;
			String digitalSignature = encoder.encode(key);
			String path = request.getContextPath();
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
			String resetPassHref =  basePath+"services/auth/resetpassword/"+digitalSignature+"/"+user.getUserid();
			String emailContent = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href="+resetPassHref +" target='_BLANK'>点击我重新设置密码</a>" +
					"<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'";
			SendMail sendMail = new SendMail();
			sendMail.sendMail(emailContent,user.getUseremail());
			msg="邮件已发送，链接有效期为半小时，请到邮箱查收";
		}catch (Exception e){
			e.printStackTrace();
			msg="邮箱不存在？未知错误,联系管理员吧。";
		}
		map.put("msg",msg);
		return map;
	}

	@RequestMapping(method=RequestMethod.GET, value="/resetpassword/{sid}/{userid}")
	public String resetPassword(HttpServletRequest request,@PathVariable String sid,@PathVariable String userid){
		String msg = "";
		if(sid.equals("") || userid.equals("")){
			msg="链接不完整,请重新生成";
			return "forward:/errorMessage.html";
		}
		User user = userService.findUserByUserId(userid);
		if(user == null){
			msg = "链接错误,无法找到匹配用户,请重新申请找回密码.";
			return "forward:/errorMessage.html";
		}
		Timestamp outDate = user.getOutdate();
		if(outDate.getTime() <= System.currentTimeMillis()){         //表示已经过期
			msg = "链接已经过期,请重新申请找回密码.";
			return "forward:/errorMessage.html";
		}
		String key = user.getUsername()+"$"+outDate.getTime()/1000*1000+"$"+user.getValidatecode();          //数字签名
		if(!encoder.matches(key, sid)) {
			msg = "链接失效";
			return msg;
		}
		setSessionUser(request,user);
		return "forward:/resetPass.html";
	}

	@RequestMapping(method=RequestMethod.POST, value="/changepassword/{newpasswd}")
	public @ResponseBody Map changePassword(HttpServletRequest request,HttpSession session,@PathVariable String newpasswd){
		Map map = new HashMap<String ,String >();
		String msg = "修改成功";
		User user = getSessionUser(request);
		user.setPassword(newpasswd);
		userService.update(user);
		session.removeAttribute(CommonConstant.USER_CONTEXT);
		map.put("msg",msg);
		return map;
	}
}

